package com.hyb.algorithm.data.struct.list;

/**
 * @Author: huyanbing
 * @Date: 2021/9/22 11:10 上午
 *
 * 725. 分隔链表
 * https://leetcode-cn.com/problems/split-linked-list-in-parts/
 *
 */
public class SplitListToParts {


    public ListNode[] splitListToParts(ListNode head, int k) {


        if(k<=0){
            return new ListNode[k];
        }

        if(head==null){
            return new ListNode[k];
        }
        //1、先计算连表的长度
        //2、n/k=quotient  remainder=n%k 前remainder 长度为  n/k+1 也就是quotient+1

        int n=0;
        ListNode dumpHead=head;
        while(dumpHead!=null){
            n++;
            dumpHead=dumpHead.next;
        }

        int quotient=n/k;
        int remainder=n%k;

        ListNode[] listArr=new ListNode[k];

        ListNode curr=head;
        int i=0;
        while(i<k&&curr!=null){
            listArr[i]=curr;

            int len=i>=remainder?quotient:quotient+1;
            for(int j=1;j<len;j++){
                curr=curr.next;
            }
            if(curr!=null){
                ListNode next=curr.next;
                curr.next=null;
                curr=next;
            }
            i++;
        }


        return listArr;


    }
}
